package com.qf.ability.message.utils;

import com.qf.ability.message.entity.Email;
import com.qf.commons.core.utils.ApplicationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Slf4j
public class SendMailUtils {

    private static JavaMailSender javaMailSender;
    static {
        javaMailSender = ApplicationUtils.getBean(JavaMailSender.class);
    }

    /**
     * 发送邮件
     */
    public static void sendMail(Email email){
        //MimeMessage代表一封邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //给邮件设置属性 - 装饰者模式
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //设置属性
            //邮件的标题
            mimeMessageHelper.setSubject(email.getSubject());
            //发件人
            mimeMessageHelper.setFrom("guidaoma@sina.com");
            //收件人
            mimeMessageHelper.setTo(email.getRecevers());
            //内容
            mimeMessageHelper.setText(email.getContent(), true);
            //发送时间
            mimeMessageHelper.setSentDate(new Date());
            //附件
            if (email.getAttm() != null) {
                mimeMessageHelper.addAttachment(email.getAttm().getName(), email.getAttm());
            }

            //发送邮件
            javaMailSender.send(mimeMessage);
            log.info("[send mail] - 邮件发送成功！");
        } catch (MessagingException e) {
            log.error("[send mail] - 邮件发送失败！", e);
        }
    }
}
